<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/1
 * Time: 10:21
 */

namespace app\controllers;
use app\models\Pet;
use app\models\User;
use app\models\UserExt;
use app\models\UserPet;
use Yii;
use yii\web\Controller;
use yii\web\Response;

class PrizeController extends Controller
{
    public function actionIndex()
    {
        if (Yii::$app->user->isGuest) {
            return $this->asJson(['code' => 10001, 'msg' => '未登录']);
        }
        $userId = Yii::$app->user->identity->user_id;
        $userExt = new UserExt();
        $userExtRow = $userExt->find()->where('user_id=:user_id', [':user_id' => $userId])->one();
        $residue = 3 - $userExtRow->limit_prize;
        return $this->render('index', ['userPetRow' => $userExtRow, 'residue' => $residue]);
    }
    /**
     * 抽奖
     * @author lizhi7  <lizhi7@xin.com>
     */
    public function actionAdd()
    {
        if (Yii::$app->user->isGuest) {
            return $this->asJson(['code' => 10001, 'msg' => '未登录']);
        }
        if (Yii::$app->user->identity->balance < 10) {
            return $this->asJson(['code' => 10002, 'msg' => '您的余额不足']);
        }
        $tran = Yii::$app->db->beginTransaction();
        try {
            $userId = Yii::$app->user->identity->user_id;
            $userExt = new UserExt();
            $userExtRow = $userExt->find()->where('user_id=:user_id', [':user_id' => $userId])->one();
            if(empty($userExtRow) || ($userExtRow->limit_prize == 3)) {
                return $this->asJson(['code' => 10003, 'msg' => '您的抽奖次数已用完']);
            }
            $User = new User();
            $result = $User->reduceBlance($userId, 10);//扣除余额

            //资金明细接口
            //资金日志
            //生成宠物
            $Pet = new Pet();
            $petId = $Pet->addDefaultPet();
            $userPet = new UserPet();

            $userExtRow->limit_prize = $userExtRow->limit_prize + 1;
            $result1 = $userExtRow->save();
            $userPet->user_id = $userId;
            $userPet->pid = $petId;
            $userPet->ascription_status = 1;
            $result2 = $userPet->save();
            if (($petId >0) && !empty($result1) && !empty($result2) && !empty($result)) {
                $tran->commit();
                return $this->asJson(['code' => 10000, 'msg' => '恭喜您抽到一只玩客猪']);
            }
            return $this->asJson(['code' => 10005, 'msg' => '系统出现异常，请耐心等候']);
        } catch (\Exception $e) {
            //回滚
            $tran->rollBack();
            echo  "rollback";
        }
    }
}